import axios from 'axios'
// import qs from 'qs'
import { MessageBox } from 'element-ui'
axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// axios.defaults.baseURL = 'http://47.108.140.211:8888'

export const req = request()

export const rest = {
  create (url, params) {
    return req.post(url, params, {
      method: 'post',
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  delete (url, params) {
    if (url && params) {
      url += '/' + params.id
    }
    return url ? req.delete(url, {
      headers: { token: localStorage.getItem('token') }
    }) : null
  },
  put (url, id, params) {
    url += '/' + id
    return url ? req.put(url, params, {
      headers: { token: localStorage.getItem('token') }
    }) : null
  },
  post (url, params) {
    return req.post(url, JSON.stringify(params), {
      headers: { token: localStorage.getItem('token') }
    }) // qs.stringify(params)
  },
  get (url, params) {
    if (url && params) {
      const ix = url.indexOf('?')
      url += (ix > -1 ? '&' : '?') +
        (typeof params === 'string' ? params : JSON.stringify(params)) // qs.stringify()
    }
    return url ? req.get(url, {
      headers: { token: localStorage.getItem('token') }
    }) : null
  }
}
export function request (config) {
  config = config || {}
  if (!config['headers']) {
    config.headers = {}
  }
  config.headers['X-Requested-With'] = 'XMLHttpRequest'

  const instance = axios.create(config)
  instance.interceptors.response.use(res => {
    if (res.status !== 200) {
      return Promise.reject(res)
    }
    const code = res.data.code
    switch (code) {
      case 400: // 未登录
        msgConfirm(res.data.msg)
        return res
      case 200:
        return res.data
      default:
        msgConfirm(res.data.msg)
        return res
    }
  }, err => {
    let status
    let error
    if (err.response) {
      msgConfirm(err.response.data.msg)
      status = err.response.status
      let data = err.response.data
      error = typeof data === 'object' ? {
        ...err,
        status,
        ...err.response.data
      } : {
        ...err,
        status,
        message: data
      }
    } else if (err.request) {
      status = err.request.status
    }
    if (!err.response) {
      // 请求超时状态
      console.log(err)
      // msgConfirm(err)
      return
    }
    return Promise.reject(error || {
      status,
      ...err
    })
  })
  return instance
}
function msgConfirm (message, title) {
  return MessageBox.confirm(message, title ? title : '温馨提示', {
    confirmButtonText: '确定',
    type: 'error',
    closeOnClickModal: false,
    closeOnPressEscape: false,
    showClose: false,
    showCancelButton: false
  })
}
